//
//  RZImageSlideViewController.m
//  RZIM
//
//  Created by reyzhang on 2021/8/25.
//

#import "RZImageSlideViewController.h"
#import <SDWebImage/SDWebImage.h>
#import "RZImageMessageProgressView.h"
#import <Photos/Photos.h>
#import "RZKitUtility.h"

@interface RZImageSlideViewController ()<UIScrollViewDelegate>
// scrollView
@property (nonatomic, strong) UIScrollView *scrollView;
//当前图片消息的数据模型
@property (nonatomic, strong) NSMutableArray<RZMessageInfo *> *imageArray;
//当前图片消息的index
@property (nonatomic, assign) NSInteger currentIndex;
//当前图片的View
@property (nonatomic, strong) UIImageView *currentImageView;
//滑动时的offset
@property (nonatomic, assign) CGFloat newContentOffsetX;
@property (nonatomic, assign) CGFloat offsettest;
@property (nonatomic, assign) CGFloat ContentOffset;
@property (nonatomic, assign) NSInteger preSelectIndex;


//图片列表
@property (nonatomic, strong) NSMutableArray<UIImageView *> *imageViewList;
@property (nonatomic, strong) NSMutableArray<RZImageMessageModel *> *imagemessageList;
@property (nonatomic, strong) NSMutableDictionary *imageProgressList;
@end

@implementation RZImageSlideViewController {
    BOOL _statusBarHidden;
}


#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.imageProgressList = [NSMutableDictionary new];
    //获取数据
    [self getMessageFromModel:self.messageModel];
    
    //ui
    self.scrollView = [[UIScrollView alloc]
        initWithFrame:CGRectMake(0, 0, (self.view.bounds.size.width + 20), self.view.bounds.size.height)];
    [self.scrollView setBackgroundColor:[UIColor blackColor]];
    [self.scrollView setDelegate:self];
    [self.scrollView setPagingEnabled:YES];
    [self.scrollView setShowsHorizontalScrollIndicator:NO];
    [self.scrollView setShowsVerticalScrollIndicator:NO];
    
    //根据数据多少来设置contentsize
    [self.scrollView setContentSize:CGSizeMake([self.imageArray count] * (self.view.bounds.size.width + 20), 0)];
    
    //长按可选择是否保存图片
    UILongPressGestureRecognizer *longPress =
        [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
    
    self.imageViewList = [NSMutableArray new];
    self.imagemessageList = [NSMutableArray new];
    self.currentImageView = [UIImageView new];
    
    
    //添加图片到scroll子视图
    [self refreshimage:self.imageArray];
    [self refreshScrollView:self.imageViewList];

    self.ContentOffset = 0;
    self.offsettest = 0.0;
    self.scrollView.contentOffset = CGPointMake(self.currentIndex * (self.view.bounds.size.width + 20), 0);
    self.ContentOffset = self.currentIndex * (self.view.bounds.size.width + 20);
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (self.imageViewList.count > self.currentIndex) {
        self.currentImageView = self.imageViewList[self.currentIndex];
    }

    [self.view addSubview:self.scrollView];
    [self.view addGestureRecognizer:longPress];
    [self performSelector:@selector(setStatusBarHidden:) withObject:@(YES) afterDelay:0.4];
    
}




- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (BOOL)prefersStatusBarHidden {
    return _statusBarHidden;
}

- (void)setStatusBarHidden:(NSNumber *)hidden {
    _statusBarHidden = [hidden boolValue];
    [UIView animateWithDuration:0.25
                     animations:^{
                         [self setNeedsStatusBarAppearanceUpdate];
                     }];
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
}
#pragma mark - Target Action
- (void)singleTap:(UITapGestureRecognizer *)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)doubleTap:(UITapGestureRecognizer *)sender {
    UIScrollView *subview = self.scrollView.subviews[self.currentIndex];
    if (subview.contentSize.width > self.view.frame.size.width) {
        [subview setZoomScale:1.0 animated:YES];
    } else {
        CGPoint touchPoint = [sender locationInView:subview];
        CGFloat newZoomScale = subview.maximumZoomScale;
        CGFloat xsize = self.view.frame.size.width / newZoomScale;
        CGFloat ysize = self.view.frame.size.height / newZoomScale;
        [subview zoomToRect:CGRectMake(touchPoint.x - xsize / 2, touchPoint.y - ysize / 2, xsize, ysize) animated:YES];
    }
}

- (void)longPressed:(id)sender {
    UILongPressGestureRecognizer *press = (UILongPressGestureRecognizer *)sender;
    if (press.state == UIGestureRecognizerStateEnded) {
        return;
    } else if (press.state == UIGestureRecognizerStateBegan) {
        //TODO:
        UIAlertController *sheet = [UIAlertController alertControllerWithTitle:@"" message:@"保存图片" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self saveImage];
        }];
        [sheet addAction:cancel];
        [sheet addAction:confirm];
        [self presentViewController:sheet animated:YES completion:nil];
    }
}

- (void)saveImage {
    //判断授权状态
       PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
       if (status == PHAuthorizationStatusAuthorized) {
           //已授权
           [self beginSaveImage];
       }else if(status == PHAuthorizationStatusDenied) {
           //拒绝
           [RZKitUtility showAlertWithTitle:@"" message:@"请打开访问相册的权限" from:self showCancel:NO confirmHandler:^{
               
           }];
       }else if (status == PHAuthorizationStatusNotDetermined) {
           //未决定
           // 弹框请求用户授权
           [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
               if (status == PHAuthorizationStatusAuthorized) { // 用户点击了好
                   [self beginSaveImage];
               }
           }];
       }else if (status == PHAuthorizationStatusRestricted) {
           //家长控制模式限制
           [RZKitUtility showAlertWithTitle:@"" message:@"因为系统原因, 无法访问相册" from:self showCancel:NO confirmHandler:^{
               
           }];
       }
}


- (void)beginSaveImage {
    
    UIImage *image = self.imageViewList[self.currentIndex].image;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        //写入图片到相册
        PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        NSLog(@"写入图片 req%@",req);
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success == NO) {
//                [self showErrorWithMessage:@"保存授权证书失败！"];
            }else {
//                [self showSuccessWithMessage:@"保存授权证书成功"];
            }
        });
        
    }];
}

#pragma mark - Private method

////取当前界面中一定数量的图片
- (void)getMessageFromModel:(RZMessageInfo *)model {
    if (!model) {
        NSLog(@"Parameters are not allowed to be nil");
        return;
    }
    NSMutableArray *ImageArr = [[NSMutableArray alloc] init];
    if (self.onlyPreviewCurrentMessage) {
        [ImageArr addObject:model];
    } else {
//        NSArray *imageArrayForward = [self getOlderMessagesThanModel:model count:5 times:0];
//        NSArray *imageArrayBackward = [self getLaterMessagesThanModel:model count:5 times:0];
//        for (NSInteger j = [imageArrayForward count] - 1; j >= 0; j--) {
//            RCMessage *rcMsg = [imageArrayForward objectAtIndex:j];
//            if (rcMsg.content) {
//                RCMessageModel *modelindex = [RCMessageModel modelWithMessage:rcMsg];
//                [ImageArr addObject:modelindex];
//            }
//        }
        [ImageArr addObject:model];
//        for (int i = 0; i < [imageArrayBackward count]; i++) {
//            RCMessage *rcMsg = [imageArrayBackward objectAtIndex:i];
//            if (rcMsg.content) {
//                RCMessageModel *modelindex = [RCMessageModel modelWithMessage:rcMsg];
//                [ImageArr addObject:modelindex];
//            }
//        }
    }

    self.imageArray = ImageArr;
    for (int i = 0; i < ImageArr.count; i++) {
        RZMessageInfo *modelindex1 = [ImageArr objectAtIndex:i];
        
        //取当前展示的图片所在有位置索引
        if (model.mid == modelindex1.mid) {
            self.currentIndex = i;
            self.preSelectIndex = self.currentIndex;
        }
    }
}


/**
 填充 imageViewList的数据
 */
- (void)refreshimage:(NSMutableArray *)imagearray {
    [self.imageViewList removeAllObjects];
    [self.imagemessageList removeAllObjects];

    for (int i = 0; i < imagearray.count; i++) {
        RZMessageInfo *model = imagearray[i];
        RZImageMessageModel *imageMessage = (RZImageMessageModel *)model.extraInfo;
        if (imageMessage) {
            [self.imagemessageList addObject:imageMessage];
            
            //创建imageview
            UIImageView *imageView = [[UIImageView alloc] init];
            imageView.tag = i + 1;
            
            //创建 加载进度view
            RZImageMessageProgressView *imageProressView =
                [[RZImageMessageProgressView alloc] initWithFrame:CGRectMake(0, 0, 135, 135)];
            imageProressView.label.hidden = YES;
            imageProressView.indicatorView.color = [UIColor blackColor];
            imageProressView.backgroundColor = [UIColor clearColor];
            [imageProressView
                setCenter:CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2)];
            [imageView addSubview:imageProressView];
            
            //加载数据
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.msg] placeholderImage:imageMessage.thumbImage options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                [imageProressView startAnimating];
            } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                [imageProressView stopAnimating];
            }];
        
           
            //调整图片大小 布局
            [self resizeSubviews:imageView];
            [self resetProgressViewFrame:imageView];
            [self.imageViewList addObject:imageView];
        }
    }
}

//调整图片大小
- (void)resizeSubviews:(UIImageView *)ImageView {
    ImageView.contentMode = UIViewContentModeScaleAspectFit;
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    UIImage *image = ImageView.image;
    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;
    if (imageWidth < 400) {
        /*
         图宽＜400px，高＜屏幕高 宽不变，高不变，水平垂直居中屏幕展示
         图宽＜400px，高≥屏幕高 宽不变，高不变，水平居中，垂直方向从图片顶端开始展示
         */
        [ImageView setFrame:CGRectMake(0, 0, imageWidth, imageHeight)];
        if (imageHeight < height) {
            ImageView.center = self.view.center;
        } else {
            ImageView.center = CGPointMake(width / 2, imageHeight / 2);
        }
    } else {
        /*
         图宽大于等于400 宽适配屏幕宽，高等比放大或缩小  放大或缩小后的高＜屏幕高，垂直居中屏幕显示
         放大或缩小后的高≥屏幕高，垂直方向从图片顶端开始展示
         */
        CGFloat scale = imageHeight / imageWidth;
        imageWidth = width;
        imageHeight = width * scale;
        [ImageView setFrame:CGRectMake(0, 0, imageWidth, imageHeight)];
        if (imageHeight < height) {
            ImageView.center = self.view.center;
        }
    }
}

- (void)resetProgressViewFrame:(UIImageView *)imageView {
    if (imageView.subviews.count > 0) {
        for (UIView *subView in imageView.subviews) {
            if ([subView isKindOfClass:[RZImageMessageProgressView class]] && subView.hidden == NO) {
                if (CGPointEqualToPoint(imageView.center, self.view.center)) {
                    [subView setCenter:CGPointMake(imageView.frame.size.width / 2, imageView.frame.size.height / 2)];
                } else {
                    [subView setCenter:CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2)];
                }
                break;
            }
        }
    }
}


- (void)refreshScrollView:(NSMutableArray *)imageViewList {

    while (self.scrollView.subviews.count > 0) {
        [self.scrollView.subviews[0] removeFromSuperview];
    }

    for (int i = 0; i < imageViewList.count; i++) {
        
        RZMessageInfo *model = self.imageArray[i];
        // scrollView
        UIScrollView *imagesrcoll =
            [[UIScrollView alloc] initWithFrame:CGRectMake(i * self.view.frame.size.width, 0,
                                                           self.view.frame.size.width, self.view.frame.size.height)];
        [imagesrcoll setContentSize:CGSizeMake(self.view.bounds.size.width, 0)];
        imagesrcoll.delegate = self;

//        UIImageView *imageView = imageViewList[i]; //从数据中读取
        
        //创建新的
        UIImageView *newImageView = [[UIImageView alloc]
            initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        newImageView.contentMode = UIViewContentModeScaleAspectFit;
//        newImageView.image = self.imagemessageList[i].thumbImage;
        
        RZImageMessageProgressView *imageProressView =
            [[RZImageMessageProgressView alloc] initWithFrame:CGRectMake(0, 0, 135, 135)];
        imageProressView.label.hidden = YES;
        imageProressView.indicatorView.color = [UIColor blackColor];
        imageProressView.backgroundColor = [UIColor clearColor];
        [imageProressView
            setCenter:CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2)];
        [newImageView addSubview:imageProressView];
        
        RZImageMessageModel *imageMessage = self.imagemessageList[i];
        //加载数据
        [newImageView sd_setImageWithURL:[NSURL URLWithString:model.msg] placeholderImage:imageMessage.thumbImage options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            [imageProressView startAnimating];
        } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            [imageProressView stopAnimating];
        }];
    
        
        
        [self resizeSubviews:newImageView];
        [imagesrcoll addSubview:newImageView];
        UITapGestureRecognizer *singleTap =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        [imagesrcoll addGestureRecognizer:singleTap];

        //双击放大或缩小
        UITapGestureRecognizer *doubleTap =
            [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
        [singleTap requireGestureRecognizerToFail:doubleTap];
        doubleTap.numberOfTapsRequired = 2;
        imagesrcoll.userInteractionEnabled = YES;
        [imagesrcoll addGestureRecognizer:doubleTap];

        [self.scrollView addSubview:imagesrcoll];

        imagesrcoll.minimumZoomScale = 1.0;
        imagesrcoll.maximumZoomScale = 4.0;
        [imagesrcoll setZoomScale:1.0];
    }
}


#pragma mark - UIScrollViewDelegate

// scrollView 开始拖动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.newContentOffsetX = self.scrollView.contentOffset.x;
    if (self.scrollView != scrollView) {
        return;
    }

    if (self.newContentOffsetX < self.ContentOffset && self.currentIndex <= (self.imageViewList.count - 1)) {
        self.currentImageView = self.imageViewList[self.currentIndex];
    }

    if (self.currentIndex >= self.imagemessageList.count)
        return;
    if (self.currentIndex >= self.imageViewList.count)
        return;

    self.currentIndex = scrollView.contentOffset.x / (self.view.bounds.size.width + 20);

//    RZImageMessageModel *cImageMessage = self.imagemessageList[self.currentIndex];
//    UIImageView *cImageView = self.imageViewList[self.currentIndex];
//
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    if ([scrollView.subviews count] > 0) {
        return scrollView.subviews[0];
    } else {
        return nil;
    }
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    [self setImageCenter:scrollView];
}

- (void)setImageCenter:(UIScrollView *)scrollView {
    UIScrollView *subview = self.scrollView.subviews[self.currentIndex];
    CGFloat offsetX = (subview.frame.size.width > subview.contentSize.width)
                          ? (subview.frame.size.width - subview.contentSize.width) * 0.5
                          : 0.0;
    CGFloat offsetY = (subview.frame.size.height > subview.contentSize.height)
                          ? (subview.frame.size.height - subview.contentSize.height) * 0.5
                          : 0.0;
    for (UIView *subView in scrollView.subviews) {
        if ([subView isKindOfClass:[UIImageView class]]) {
            subView.center =
                CGPointMake(subview.contentSize.width * 0.5 + offsetX, subview.contentSize.height * 0.5 + offsetY);
        }
    }
}

@end
